<?php

// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Core" and is released under
// the MIT License terms.

// As far as I can say, this does not violate LGPL.
// Check last paragraph of https://www.gnu.org/licenses/lgpl-java.html

namespace Hawese\Core;

use PHPMailer\PHPMailer\PHPMailer;
use JsonSerializable;

/**
 * Mailer class
 *
 * This class shouldn't be directly called, since its instantiation is
 * already configured in ./Providers/MailerServiceProvider.php.
 *
 * Create a ready-to-go instance using `app(\Hawese\Core\Mailer::class)`.
 */
class Mailer extends PHPMailer implements JsonSerializable
{
    public function send(): bool
    {
        // Really send only on production, else dump mail into log file
        if (app()->environment() == 'production') {
            return parent::send(); // @codeCoverageIgnore
        } else {
            $this->preSend();
            app('log')->info($this->getSentMIMEMessage());
            return true;
        }
    }

    public function jsonSerialize()
    {
        return [
            'From' => $this->From,
            'FromName' => $this->FromName,
            'Subject' => $this->Subject,
            'To' => array_map('static::maskToEmail', $this->getToAddresses())
        ];
    }

    protected static function maskToEmail(array $to): array
    {
        return [
            preg_replace_callback(
                '/(?<=^\w).*(?=\w@.+$)/',
                function ($matches) {
                    return str_repeat('*', strlen($matches[0]));
                },
                $to[0]
            ),
            $to[1]
        ];
    }
}
